package com.dagene.weixin.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.http.client.ClientProtocolException;

import com.dagene.weixin.bean.AccessToken;
import com.dagene.weixin.bean.NewsArticle;

/**
 * 上传素材
 * 
 * @author wangjl
 * 
 */
public class UploadUtil {
	HttpUtil httpUtil = new HttpUtil();
	String httputilUrl;
	AccessToken at = null;

	public UploadUtil() {
		at = httpUtil.getAccessToken(Constants.APPID, Constants.APPSECRET);
	}

	public String postImg(String filePath) {
		httputilUrl = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=image";
		httputilUrl = httputilUrl.replace("ACCESS_TOKEN", at.getToken());

		File file = new File(filePath);
		if (!file.exists())
			return null;
		String result = null;
		try {
			URL url1 = new URL(httputilUrl);
			HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
			conn.setConnectTimeout(5000);
			conn.setReadTimeout(30000);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setRequestProperty("Cache-Control", "no-cache");
			String boundary = "-----------------------------"
					+ System.currentTimeMillis();
			conn.setRequestProperty("Content-Type",
					"multipart/form-data; boundary=" + boundary);

			OutputStream output = conn.getOutputStream();
			output.write(("--" + boundary + "\r\n").getBytes());
			/* media参数，form-data中媒体文件标识，有filename、filelength、content-type等信息 */
			output.write(String
					.format("Content-Disposition: form-data; name=\"media\"; filename=\"%s\"\r\n",
							file.getName()).getBytes());
			output.write("Content-Type: image/jpeg \r\n\r\n".getBytes());
			byte[] data = new byte[1024];
			int len = 0;
			FileInputStream input = new FileInputStream(file);
			while ((len = input.read(data)) > -1) {
				output.write(data, 0, len);
			}
			output.write(("\r\n--" + boundary + "\r\n\r\n").getBytes());
			output.flush();
			output.close();
			input.close();
			InputStream resp = conn.getInputStream();
			StringBuffer sb = new StringBuffer();
			while ((len = resp.read(data)) > -1)
				sb.append(new String(data, 0, len, "utf-8"));
			resp.close();
			result = sb.toString();
			System.out.println(result);
		} catch (ClientProtocolException e) {
			// ("postFile，不支持http协议", e);
		} catch (IOException e) {
			// log.error("postFile数据传输失败", e);
		}
		System.out.println(result);
		return result;
	}

	public String uploadNews(List<NewsArticle> articles) throws Exception {
		httputilUrl = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=ACCESS_TOKEN&type=image";
		httputilUrl = httputilUrl.replace("ACCESS_TOKEN", at.getToken());

		String jsonStr = JSONArray.fromObject(articles).toString();
		String jsonMessage = "{\"articles\":" + jsonStr + "}";
		JSONObject jsonObject = new HttpUtil().httpPostRequest(httputilUrl,
				"POST", jsonMessage);
		System.out.println("news_result: " + jsonObject);
		if (!jsonObject.containsKey("errcode")) {
			return jsonObject.toString();
		} else {
			throw new Exception("NewsArticle上传异常：" + jsonObject.toString());
		}
	}

}
